
package brian.huang.reader;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.widget.ScrollView;
import android.widget.Scroller;

public class ReaderView extends ScrollView {
    private static final String TAG = "ReaderView";
    private View mTop;
    private View mView;
    private View mBottom;
    private Scroller mScroller;
    private boolean mScrolling;
    private ScrollCompletedListener mListener;

    public interface ScrollCompletedListener {
        public void onScrollCompleted();
    }

    public ReaderView(Context context) {
        this(context, null);
    }

    public ReaderView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ReaderView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        mTop = findViewById(R.id.topWindow);
        mView = findViewById(R.id.viewWindow);
        mBottom = findViewById(R.id.bottomWindow);

        mScroller = new Scroller(getContext(), new LinearInterpolator());
        mScrolling = false;
    }

    public void start(int viewHeight, int duration, ScrollCompletedListener listener) {
        mListener = listener;
        setVisibility(View.VISIBLE);
        setLayoutHeight(mTop, getHeight());
        setLayoutHeight(mView, viewHeight);
        setLayoutHeight(mBottom, getHeight());
        int scrollHeight = getHeight() + viewHeight;
        mScroller.startScroll(getScrollX(), scrollHeight, 0, -scrollHeight, duration);
        mScrolling = true;
    }

    public void stop() {
        setLayoutHeight(mTop, 0);
        setLayoutHeight(mView, 0);
        setLayoutHeight(mBottom, 0);
        setVisibility(View.INVISIBLE);
        mScroller.abortAnimation();
        mScrolling = false;
    }

    private void setLayoutHeight(View view, int height) {
        ViewGroup.LayoutParams params = view.getLayoutParams();
        params.height = height;
        view.setLayoutParams(params);
    }

    @Override
    public void computeScroll() {
        if (mScroller.computeScrollOffset()) {
            setScrollY(mScroller.getCurrY());
            postInvalidate();
        } else {
            if (mScrolling) {
                mScrolling = false;
                setLayoutHeight(mTop, 0);
                setLayoutHeight(mView, 0);
                setLayoutHeight(mBottom, 0);
                setVisibility(View.GONE);
                if (mListener != null) {
                    mListener.onScrollCompleted();
                }
            }
            super.computeScroll();
        }
    }
}
